package com.ruoyi.pos.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.enums.AuditStatusEnum;
import com.ruoyi.common.enums.TransOperTypeEnum;
import com.ruoyi.common.enums.TransTypeEnum;
import com.ruoyi.common.enums.WithdrawStatusEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.qugongbao.QugongbaoUtils;
import com.ruoyi.common.utils.weCat.WeCatUtils;
import com.ruoyi.common.utils.weCat.template.RefuseTemplate;
import com.ruoyi.pos.api.service.common.ICommonService;
import com.ruoyi.pos.api.utils.CommonUtils;
import com.ruoyi.pos.web.domain.TRebateSetInfo;
import com.ruoyi.pos.web.domain.TUserDefaultInfo;
import com.ruoyi.pos.web.domain.TUserInfo;
import com.ruoyi.pos.web.mapper.TUserDefaultInfoMapper;
import com.ruoyi.pos.web.mapper.TUserInfoMapper;
import com.ruoyi.pos.web.service.ITUserDefaultInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 用户出入账信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-11-24
 */
@Service
public class TUserDefaultInfoServiceImpl implements ITUserDefaultInfoService 
{
    private static final Logger log = LoggerFactory.getLogger(TUserDefaultInfoServiceImpl.class);
    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private TUserDefaultInfoMapper tUserDefaultInfoMapper;
    @Autowired
    private ICommonService commonService;
    @Autowired
    Environment env;
    @Autowired
    WeCatUtils weCatUtils;
    @Autowired
    QugongbaoUtils qugongbaoUtils;
    @Autowired
    private CommonUtils commonUtils; //公共业务处理类

    /**
     * 查询用户出入账信息
     * 
     * @param id 用户出入账信息主键
     * @return 用户出入账信息
     */
    @Override
    public TUserDefaultInfo selectTUserDefaultInfoById(String id)
    {
        TUserDefaultInfo mapper = new TUserDefaultInfo();
        mapper.setId(id);
        //mapper.setTransType(TransTypeEnum.YUE.getCode());
        //mapper.setTransOperType(TransOperTypeEnum.YUE_1003.getCode());
        List<TUserDefaultInfo> list = tUserDefaultInfoMapper.selectTUserDefaultInfoListForWeb(mapper);
        //TUserDefaultInfo defaultInfo = list.size() > 0 ? list.get(0) : new TUserDefaultInfo();
        list.stream().forEach(bean ->{
            if (StringUtils.isNotEmpty(bean.getCheckStatus())) {
                bean.setCheckStatusShow(AuditStatusEnum.getEnumsByCode(bean.getCheckStatus()).getValue());
            }
        });
        return list.get(0);
    }

    /**
     * 查询用户出入账信息列表
     * 
     * @param tUserDefaultInfo 用户出入账信息
     * @return 用户出入账信息
     */
    @Override
    public List<TUserDefaultInfo> selectTUserDefaultInfoList(TUserDefaultInfo tUserDefaultInfo)
    {
        tUserDefaultInfo.setTransType(TransTypeEnum.YUE.getCode());
        tUserDefaultInfo.setTransOperType(TransOperTypeEnum.YUE_1003.getCode());
        if (null != tUserDefaultInfo.getQueryCreateTimeStr()) {
            tUserDefaultInfo.setCreateTimeStart(tUserDefaultInfo.getQueryCreateTimeStr()[0] + " 00:00:00");
            tUserDefaultInfo.setCreateTimeEnd(tUserDefaultInfo.getQueryCreateTimeStr()[1] + " 23:59:59");
        }
        if (null != tUserDefaultInfo.getQueryCheckTimeStr()) {
            tUserDefaultInfo.setCheckTimeStart(tUserDefaultInfo.getQueryCheckTimeStr()[0] + " 00:00:00");
            tUserDefaultInfo.setCheckTimeEnd(tUserDefaultInfo.getQueryCheckTimeStr()[1] + " 23:59:59");
        }
        if (null != tUserDefaultInfo.getQueryPayTimeStr()) {
            tUserDefaultInfo.setPayTimeStart(tUserDefaultInfo.getQueryPayTimeStr()[0] + " 00:00:00");
            tUserDefaultInfo.setPayTimeEnd(tUserDefaultInfo.getQueryPayTimeStr()[1] + " 23:59:59");
        }
        List<TUserDefaultInfo> list = tUserDefaultInfoMapper.selectTUserDefaultInfoListForWeb(tUserDefaultInfo);
        list.stream().forEach(bean ->{
            if (StringUtils.isNotEmpty(bean.getCheckStatus())) {
                bean.setCheckStatusShow(AuditStatusEnum.getEnumsByCode(bean.getCheckStatus()).getValue());
            }
            if (StringUtils.isNotEmpty(bean.getWithdrawStatus())) {
                bean.setWithdrawStatusShow(WithdrawStatusEnum.getEnumsByCode(bean.getWithdrawStatus()).getValue());
            }
        });
        return list;
    }

    /**
     * 新增用户出入账信息
     * 
     * @param tUserDefaultInfo 用户出入账信息
     * @return 结果
     */
    @Override
    public int insertTUserDefaultInfo(TUserDefaultInfo tUserDefaultInfo)
    {
        tUserDefaultInfo.setCreateTime(DateUtils.getNowDate());
        return tUserDefaultInfoMapper.insertTUserDefaultInfo(tUserDefaultInfo);
    }

    /**
     * 修改用户出入账信息
     * 
     * @param tUserDefaultInfo 用户出入账信息
     * @return 结果
     */
    @Override
    public int updateTUserDefaultInfo(TUserDefaultInfo tUserDefaultInfo)
    {
        tUserDefaultInfo.setUpdateTime(DateUtils.getNowDate());
        return tUserDefaultInfoMapper.updateTUserDefaultInfo(tUserDefaultInfo);
    }

    /**
     * 批量删除用户出入账信息
     * 
     * @param ids 需要删除的用户出入账信息主键
     * @return 结果
     */
    @Override
    public int deleteTUserDefaultInfoByIds(String[] ids)
    {
        return tUserDefaultInfoMapper.deleteTUserDefaultInfoByIds(ids);
    }

    /**
     * 删除用户出入账信息信息
     * 
     * @param id 用户出入账信息主键
     * @return 结果
     */
    @Override
    public int deleteTUserDefaultInfoById(String id)
    {
        return tUserDefaultInfoMapper.deleteTUserDefaultInfoById(id);
    }

    //审核通过
    @Override
    @Transactional
    public int checkPass(TUserDefaultInfo tUserDefaultInfo) throws Exception {
        TUserDefaultInfo newDefault = tUserDefaultInfoMapper.selectTUserDefaultInfoById(tUserDefaultInfo.getId());
        if (!AuditStatusEnum.WAIT_AUDIT.getCode().equals(newDefault.getCheckStatus())) {
            throw new RuntimeException("当前提现审核状态为：" + AuditStatusEnum.getEnumsByCode(newDefault.getCheckStatus()).getValue() + "，不能进行审核操作");
        }
        newDefault.setCheckStatus(AuditStatusEnum.PASS_AUDIT.getCode());
        newDefault.setCheckStatusTime(DateUtils.getNowDate());
        newDefault.setCheckStatusUserId(SecurityUtils.getLoginUser().getUser().getUserId() + "");
        //审核通过后，调用趣工宝发起支付申请
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(newDefault.getUserId());
        if (StringUtils.isEmpty(user.getMemberNo())) {
            throw new RuntimeException("该用户在趣工宝还未进行签约，无法提现");
        }
        Map<String, String> resultMap = qugongbaoUtils.withdrawalForPay(newDefault.getId(), newDefault.getId(), user.getMemberNo(), newDefault.getWithdrawAmount().multiply(new BigDecimal(100)));
        if ("0000".equals(resultMap.get("code"))) {
            String orderNo = resultMap.get("orderNo"); //趣工宝平台订单号
            newDefault.setWithdrawOrderNo(resultMap.get("orderNo")); //趣工宝平台订单号
            newDefault.setWithdrawStatus(WithdrawStatusEnum.HANDEL.getCode());
            newDefault.setWithdrawStatusTime(DateUtils.getNowDate());
        } else { //提现申请失败
            throw new RuntimeException("提现申请失败：" + resultMap.get("msg"));
        }

        /*TUserInfo user = userInfoMapper.selectTUserInfoByUserId(newDefault.getUserId());
        if (StringUtils.isNotEmpty(user.getSuperiorUserId())) {
            //提现分润，用户提现成功，直营上级会获得分润收益
            TRebateSetInfo set = commonService.queryTRebateSetInfoVo();
            TUserDefaultInfo supDefaultInfo = commonUtils.generateTUserDefaultInfo(
                    user.getSuperiorUserId(),
                    "",
                    TransTypeEnum.YUE.getCode(),
                    TransOperTypeEnum.YUE_1008.getCode(),
                    newDefault.getWithdrawAmount().multiply(set.getCarryRebate()).setScale(2, BigDecimal.ROUND_HALF_DOWN),
                    "",
                    "",
                    null,
                    "",
                    null);
            tUserDefaultInfoMapper.insertTUserDefaultInfo(supDefaultInfo);
        }
        newDefault.setWithdrawStatus(WithdrawStatusEnum.SUCCESS.getCode());
        newDefault.setWithdrawStatusTime(DateUtils.getNowDate());*/
        return tUserDefaultInfoMapper.updateTUserDefaultInfo(newDefault);
    }

    //审核不通过
    @Override
    @Transactional
    public int checkRefuse(TUserDefaultInfo tUserDefaultInfo) throws Exception {
        TUserDefaultInfo newDefault = tUserDefaultInfoMapper.selectTUserDefaultInfoById(tUserDefaultInfo.getId());
        if (!AuditStatusEnum.WAIT_AUDIT.getCode().equals(newDefault.getCheckStatus())) {
            throw new RuntimeException("当前提现审核状态为：" + AuditStatusEnum.getEnumsByCode(newDefault.getCheckStatus()).getValue() + "，不能进行审核操作");
        }
        newDefault.setCheckStatus(AuditStatusEnum.REFUSE_AUDIT.getCode());
        newDefault.setCheckStatusTime(DateUtils.getNowDate());
        newDefault.setCheckStatusUserId(SecurityUtils.getUserId() + "");
        newDefault.setCheckStatusDescribe(tUserDefaultInfo.getCheckStatusDescribe());
        //审核不通过，释放冻结的余额
        TUserInfo user = userInfoMapper.selectTUserInfoByUserId(tUserDefaultInfo.getUserId());
        user.setBalanceWithdraw(user.getBalanceWithdraw().subtract(tUserDefaultInfo.getTransAmount()));
        userInfoMapper.updateTUserInfo(user);
        //审核不通过，发送消息通知
        try { //此处捕获异常，不因公众号的异常影响审核逻辑
            TRebateSetInfo set = commonService.queryTRebateSetInfoVo();
            JSONObject first = new JSONObject();
            first.put("value", "提现审核结果通知");
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value", user.getUserName());
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value", "审核失败");
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value", DateUtils.getDate());
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value", AuditStatusEnum.REFUSE_AUDIT.getValue());
            JSONObject remark = new JSONObject();
            remark.put("value", set.getWithdrawFailResult());
            RefuseTemplate.Params data = RefuseTemplate.Params.builder()
                    .first(first)
                    .keyword1(keyword1)
                    .keyword2(keyword2)
                    .keyword3(keyword3)
                    .keyword4(keyword4)
                    .remark(remark)
                    .build();
            RefuseTemplate template = RefuseTemplate.builder()
                    .template_id(env.getProperty("wx.template.refuseTemplate"))
                    .touser(user.getOpenId())
                    .url("https://www.baidu.com/")
                    .data(data)
                    .build();
            weCatUtils.sendTemplate(template);
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        } finally {
            return tUserDefaultInfoMapper.updateTUserDefaultInfo(newDefault);
        }
    }

    @Override
    public List<TUserDefaultInfo> selectRecordList(TUserDefaultInfo userDefaultInfo) {
        return tUserDefaultInfoMapper.selectRecordList(userDefaultInfo);
    }

    @Override
    public List<TUserDefaultInfo> exchangeRecordList(TUserDefaultInfo userDefaultInfo) {
        return tUserDefaultInfoMapper.exchangeRecordList(userDefaultInfo);
    }

}
